package com.example.mybank.springSecurity;

import com.example.mybank.entity.Users;
import com.example.mybank.mapper.UsersMapper;
import com.example.mybank.tool.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Slf4j
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    UsersMapper usersMapper;

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        //更新用户表上次登录时间、更新人、更新时间等字段
        UserHandler userHandler = (UserHandler)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Users users =userHandler.getUsers();
        users.setDatetime_login(new Date());
        usersMapper.updateById(users);


        //返回json数据
        JsonResult jsonResult = JsonResult.ok(users);
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");

        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(jsonResult));
    }
}